package com.tgd.RingtoneContactManager;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ContactAdapter extends BaseAdapter {

    class ViewHolder {
        Contact contact;
        TextView tvContact;
        TextView tvRingtone;
        ImageView ivDefault;
    }

    private Contact[] _contacts;
    private LayoutInflater mInflater;

    public ContactAdapter(Context context, Contact[] contacts) {
        // Cache the LayoutInflate to avoid asking for a new one each time.
        mInflater = LayoutInflater.from(context);
        _contacts = contacts;
    }

    @Override
    public int getCount() {
        return (_contacts == null ? 0 : _contacts.length);
    }

    @Override
    public Object getItem(int position) {
        return _contacts[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.contact_row, null);

            holder = new ViewHolder();
            holder.tvContact = (TextView) convertView.findViewById(R.id.contact_row_contact);
            holder.tvRingtone = (TextView) convertView.findViewById(R.id.contact_row_ringtone);
            holder.ivDefault = (ImageView) convertView.findViewById(R.id.contact_row_default);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Contact c = _contacts[position];
        holder.contact = c;
        convertView.setTag(holder);

        holder.tvContact.setText(c.getName());
        holder.tvRingtone
                .setText((c.getRingtone() == null) ? "unknown" : c.getRingtone().getName());
        holder.ivDefault.setVisibility(c.getRingtone().isDefault() ? View.VISIBLE : View.GONE);

        return convertView;
    }

}
